package com.ruoyi.familyManagement.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.enums.BusinessCode;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.familyManagement.domain.vo.FamilyInfoAndContractedInfo;
import com.ruoyi.familyManagement.domain.vo.FamilyVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.familyManagement.domain.DocFamily;
import com.ruoyi.familyManagement.service.IDocFamilyService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 家庭表Controller
 *
 * @author ruoyi
 * @date 2025-08-14
 */
@RestController
@Api(tags = "家庭管理模块")
@RequestMapping("/familyManagement/docFamily")
public class DocFamilyController extends BaseController {
    @Autowired
    private IDocFamilyService docFamilyService;

    /**
     * 查询家庭表列表
     */
    @PreAuthorize("@ss.hasPermi('familyManagement:docFamily:list')")
    @GetMapping("/list")
    public TableDataInfo list(DocFamily docFamily) {
        startPage();
        List<DocFamily> list = docFamilyService.selectDocFamilyList(docFamily);
        return getDataTable(list);
    }

    /**
     * 导出家庭表列表
     */
    @PreAuthorize("@ss.hasPermi('familyManagement:docFamily:export')")
    @Log(title = "家庭表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DocFamily docFamily) {
        List<DocFamily> list = docFamilyService.selectDocFamilyList(docFamily);
        ExcelUtil<DocFamily> util = new ExcelUtil<DocFamily>(DocFamily.class);
        util.exportExcel(response, list, "家庭表数据");
    }

    /**
     * 获取家庭表详细信息
     */
    @PreAuthorize("@ss.hasPermi('familyManagement:docFamily:query')")
    @GetMapping(value = "/{famliyId}")
    public AjaxResult getInfo(@PathVariable("famliyId") Long famliyId) {
        return success(docFamilyService.selectDocFamilyByFamliyId(famliyId));
    }

    /**
     * 新增家庭表
     */
    @PreAuthorize("@ss.hasPermi('familyManagement:docFamily:add')")
    @Log(title = "家庭表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DocFamily docFamily) {
        return toAjax(docFamilyService.insertDocFamily(docFamily));
    }

    /**
     * 修改家庭表
     */
    @PreAuthorize("@ss.hasPermi('familyManagement:docFamily:edit')")
    @Log(title = "家庭表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DocFamily docFamily) {
        return toAjax(docFamilyService.updateDocFamily(docFamily));
    }

    /**
     * 删除家庭表
     */
    @PreAuthorize("@ss.hasPermi('familyManagement:docFamily:remove')")
    @Log(title = "家庭表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{famliyIds}")
    public AjaxResult remove(@PathVariable Long[] famliyIds) {
        return toAjax(docFamilyService.deleteDocFamilyByFamliyIds(famliyIds));
    }

    /**
     * 根据用户id查询用户家庭信息
     *
     * @return AjaxResult
     */
    @ApiOperation("根据用户id查询用户家庭信息")
    @GetMapping("/findFamilyByUserId")
    public AjaxResult findFamilyByUserId() {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        FamilyVO familyVO = docFamilyService.findFamilyByUserId(userId);
        return familyVO == null ? null : AjaxResult.success(familyVO);
    }

    /**
     * 根据用户id查询用户家庭信息和已签约列表信息
     */
    @ApiOperation("根据用户id查询用户家庭信息和已签约列表")
    @GetMapping("/findFamilyByUserIdAndContracted")
    public AjaxResult findFamilyByUserIdAndContracted() {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        // 先判断当前用户是否有家庭
        int num = docFamilyService.findFamilyIdByUserId2(userId);
        if (num == 0) {
            return null;
        }
        // 获取信息对象列表
        List<FamilyInfoAndContractedInfo> list = docFamilyService.findFamilyByUserIdAndContracted(userId);

        return AjaxResult.success(list);
    }

    /**
     * 添加家庭信息
     */
    @ApiOperation("添加家庭信息")
    @PostMapping("/addFamilyVO")
    public void addFamilyVO(@RequestBody FamilyVO familyVO) {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();
        familyVO.setUserId(userId);

        docFamilyService.insertDocFamilyVO(familyVO);
    }

    /**
     * 添加家庭中间表信息
     */
    @ApiOperation("添加家庭中间表信息")
    @PostMapping("/addFamilyUser")
    public void addFamilyUser() {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();
        // 获取当前登录用户账号
        String username = SecurityUtils.getUsername();

        docFamilyService.insertDocFamilyUser(userId, username);
    }

    /**
     * 获取家庭成员信息
     */
    @ApiOperation("获取家庭成员信息")
    @GetMapping("/getFamilyUserInfo")
    public AjaxResult getFamilyUserInfo() {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        return AjaxResult.success(docFamilyService.getFamilyUserInfo(userId));
    }

    /**
     * 根据用户账号添加家庭成员
     *
     * @param username 用户账号
     */
    @ApiOperation("添加家庭成员")
    @PostMapping("/addFamilyUser/{username}")
    public void addFamilyUser(@PathVariable String username) {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();
        docFamilyService.addFamilyUser(userId, username);
    }

    /**
     * 成员添加校验
     *
     * @param username 用户账号
     * @return AjaxResult
     */
    @ApiOperation("成员添加校验")
    @PostMapping("/checkAddFamilyUser/{username}")
    public AjaxResult checkAddFamilyUser(@PathVariable String username) {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();
        // 获取当前用户账号
        String username1 = SecurityUtils.getUsername();

        // 1、家庭成员不能超过4个
        int familyUserNum = docFamilyService.checkFamilyUserNum(userId);
        if (familyUserNum >= 4)
            return AjaxResult.success(BusinessCode.CHECK_FAMILY_USER_NUM);

        // 2、不能添加自己
        if (username1.equals(username))
            return AjaxResult.success(BusinessCode.CHECK_IS_SELF);

        // 3、未找到该成员，前端提示注册或跳转
        boolean isExist = docFamilyService.checkIsExist(username);
        if (!isExist)
            return AjaxResult.success(BusinessCode.CHECK_IS_EXIST);

        // 4、医生不能添加家庭
        boolean isDoctor = docFamilyService.checkIsDoctor(username);
        if (isDoctor)
            return AjaxResult.success(BusinessCode.CHECK_IS_DOCTOR);

        // 5、用户是否已有家庭
        boolean isTeam = docFamilyService.checkIsTeam(username);
        if (isTeam)
            return AjaxResult.success(BusinessCode.CHECK_IS_TEAM);

        return AjaxResult.success();
    }

    /**
     * 校验当前用户是否已有家庭
     *
     * @return AjaxResult
     */
    @ApiOperation("校验当前用户是否已有家庭")
    @GetMapping("/checkNotFamily")
    public AjaxResult checkNotFamily() {
        // 获取当前登录用户ID
        Long userId = SecurityUtils.getUserId();

        int num = docFamilyService.findFamilyIdByUserId2(userId);
        if (num == 0)
            return AjaxResult.success(BusinessCode.CHECK_NOT_FAMILY);

        return AjaxResult.success();
    }

}
